import {Message} from "element-ui";
import {ElUploadInternalRawFile} from "element-ui/types/upload";

export default {
  /**
   * 校验文件类型
   *@param file 当前文件
   * @param onlyIncludeFile 支持的文件类型
   * @returns boolean
   */
  checkFileType(file:ElUploadInternalRawFile,onlyIncludeFile:Array<string>,msg='请上传指定格式文件'):boolean{
    const type = 'file/'+file.name.substr(file.name.lastIndexOf(".")+1)
    const includeFile = onlyIncludeFile?onlyIncludeFile:['png', 'jpg','jpeg'];
    if (!includeFile.includes(type.split('/')[1])) {
      Message.warning(msg)
      return false
    }
    return true;
  },

  /**
   * 校验文件大小
   *@param file 当前文件
   * @param size 支持的最大大小
   * @returns boolean
   */
  checkFileSize(file:ElUploadInternalRawFile,size:number):boolean{
    if (file.size > size * 1024 * 1024) {
      Message.warning(`文件不能超过${size}M`)
      return false
    } else if(file.size <= 0) {
      Message.warning(`请检查文件大小`)
      return false
    }
    return true;
  },

  /**
   * 判断文件类型
   * @param
   */
  getFileType(file:any){
    return file.name.substr(file.name.lastIndexOf(".")+1)
  },


  //  获取音视频时长
  getDuration(file){
    return new Promise(((resolve) => {
      const  url = URL.createObjectURL(file);
      const audioElement = new Audio(url);
      let duration = '';
      audioElement.addEventListener('loadedmetadata',(e)=>{
        duration = String(audioElement.duration)
        resolve(duration)
      })
    }))
  },

  canvasToFile(canvas,fileName){
    const binStr = atob(canvas.toDataURL('image/png').split(',')[1])
    let len = binStr.length;
    const arr = new Uint8Array(len);
    while (len--){
      arr[len] = binStr.charCodeAt(len)
    }
    const filename = fileName.split('.')[0]+'.png'
    return new File([arr],filename,{type:'image/png'})
  },

  blobToImg(blob){
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.addEventListener('load',()=>{
        const img = document.createElement('img')
        img.src = reader.result as string;
        img.addEventListener('load',()=>resolve(img))
      })
      reader.readAsDataURL(blob);
    })
  },

  readURL(src){
    return new Promise((resolve, reject) => {
      const img = document.createElement('img');
      img.src = src;
      img.crossOrigin = 'anonymous';
      img.addEventListener('load', () => resolve(img))
    })
  }
}
